<template>
  <div>
    <van-nav-bar
      title="商品列表"
      left-text="返回"
      left-arrow
      @click-left="
        () => {
          $router.push('/');
        }
      "
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <!-- 商品卡片做渲染 -->
        <router-link v-for="item in list" :to="'/xiangqing/'+item.goods_id">
          <van-card :price="item.goods_price" :title="item.goods_name" >
          <!-- 手写插槽 -->
           <template #thumb>
            <img :src="item.goods_big_logo?item.goods_big_logo:'https://pic35.photophoto.cn/20150511/0034034892281415_b.jpg'" alt="" style="width: 88px;height: 88px;">
           </template>
          </van-card> 
        </router-link>
      </van-list>
    </van-pull-refresh>

    <!-- tabBar -->
    <dao></dao>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRoute } from "vue-router";
const route = new useRoute();
console.log(route.params.cat_id);

//引入tabBar
import dao from "@/components/dao.vue";

//自定义渲染数据
const list = ref([]);
//当前页
let page = ref(1);
//每页个数
let pagesize = ref(5);
//总条数
let total = ref(0);
// :loading 是否处于加载状态
let loading = ref(false);
// finished 是否已完成加载
let finished = ref(false);
// refreshing 是否刷新
let refreshing = ref(false);

import { goodsApi } from "@/api/api";
const goodsData = () => {
  goodsApi(route.params.cat_id).then((res) => {
    
    //自定义切割的下标
    let startindex=(page.value-1)*pagesize.value
    let endindex=startindex+pagesize.value
    //将所有的数据长度  赋值给total
    total.value=res.data.message.goods.length
    //处理数据
    list.value=res.data.message.goods.slice(startindex,endindex)
    //:loading 处于加载状态
    loading.value=true
    //判断  如果数据超过20条  finished 加载已完成  不加载
    if(list.value.length>=total.value){
        finished.value=true
    }
  });
};
goodsData();

//下拉刷新----onRefresh  监听下拉
const onRefresh=()=>{
    console.log('下拉')
    page.value=2
    list.value=[]
    finished.value=false
    refreshing.value=false
    goodsData()
}
//上拉加载更多  每一次加载5 等待数据回来  异步  async await
//onLoad 监听上拉
const onLoad=async()=>{
    //如果数据加载完毕  则不进行加载
    if(finished.value)return
    //下一页数据  要追加到当前list中
    //拿到第二页数据
    page.value++
    const res=await goodsApi()
    //切割第二页数据的数据  累加到第一页中
    let startindex=(page.value-1)*pagesize.value
    let endindex=startindex+pagesize.value
    let newData=res.data.message.goods.slice(startindex,endindex)
    //第一页 第二页 数据合并到一起
    list.value=[...list.value,...newData]
    //loading 不处于加载状态
    loading.value=false
    //如果 数据都加载完毕
    if(list.value.length>=total.value){
        //加载完毕
        finished.value=true
    }
}
</script>

<style lang="scss" scoped></style>
